<template>
  <el-config-provider :locale="zhCn">
    <div class="popup-content" >
      <div class="tips" >
        <span>{{ `今天是${tips}` }}</span>
        <el-button type="primary" :icon="Setting" circle @click="isShow = true" />
      </div>
      <div class="jokeTips">
        {{ `${jokeTip}` }}
      </div>
      <div class="timer-box" >
        <div class="timer-item" v-html="weekend" ></div>
        <div class="timer-item" v-html="afterWork" ></div>
        <div class="timer-item timer-item-end" v-html="salary" ></div>
      </div>
      <el-card class="card-box" v-if="isShow" >
        <el-form ref="formRef" :model="formData" :rules="formRules" label-width="90px">
          <el-form-item label="下班时间" prop="closingTime">
            <el-time-picker
              v-model="formData.closingTime"
              placeholder="请选择"
              format='HH:mm'
              value-format="HH:mm"
            />
          </el-form-item>
          <el-form-item label="点餐提醒" prop="order">
            <el-time-picker
              v-model="formData.order"
              placeholder="请选择"
              format='HH:mm:ss'
              value-format="HH:mm:ss"
            />
          </el-form-item>
          <el-form-item label="发薪日" prop="Payday">
            每月<el-input-number v-model="formData.Payday" :min="1" :max="31" />号
          </el-form-item>
          <el-form-item label="工作制" prop="WorkSystem">
            <el-radio-group v-model="formData.WorkSystem">
              <el-radio :value="1">双休</el-radio>
              <el-radio :value="2">大小周</el-radio>
              <el-radio :value="3">单休</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-button type="primary" @click="submitForm">保存</el-button>
        </el-form>
      </el-card>
    </div>
  </el-config-provider>
  
</template>
<script setup lang="js">
import { ref, onMounted, onUnmounted, onBeforeUnmount } from 'vue'
import { Setting } from '@element-plus/icons-vue'
import { preciseTimeout, durationFormatter } from '../utils/setTime'
import { randomJoke } from '../utils/generatingVulgarLanguage'
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import dayjs from 'dayjs'

const isShow = ref(false)
const formData = ref({
  closingTime: '18:00',
  order: '12:00:00',
  Payday: 15,
  WorkSystem: 1,
})

const infoData = ref({
  closingTime: '18:00',
  order: '12:00',
  Payday: 15,
  WorkSystem: 1,
})

const formRules = {
  closingTime: [{ required: true, message: '请选择下班时间', trigger: 'blur', }],
  // order: [{ required: true, message: '请选择下班时间', trigger: 'blur', }],
  Payday: [{ required: true, message: '请选择发薪日', trigger: 'blur', }],
  WorkSystem: [{ required: true, message: '请选择工作制', trigger: 'blur', }],
}

const now = new Date();
const day = ref(now.getDay());
const weeks = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];

const jokeTip = randomJoke()

const tips = ref(weeks[day.value])
// 下班
const weekend = ref()
const getWeekend = () => {
  // 获取当前时间
  const currentDate = new Date();
  const futureDate = new Date(currentDate);
  futureDate.setHours(Number(infoData.value.closingTime.split(':')[0]))
  futureDate.setMinutes(Number(infoData.value.closingTime.split(':')[1]))
  futureDate.setSeconds(0)
  const timeDifference = futureDate - currentDate
  return timeDifference/1000
}
// 工资
const salary = ref()
const getSalary = () => {
  let currentDate = new Date();
  let year = currentDate.getFullYear();
  let month = currentDate.getMonth(); // 月份从0开始计数
  let currentDay = currentDate.getDate();
  // 创建一个新的Date对象，只包含当前日期的年月日
  let currentOnlyDate = new Date(year, month, currentDay);
  // 创建一个新的Date对象，只包含年、月、日，并将日期设置为15号
  let specificDate = new Date(year, month, infoData.value.Payday);
  if (specificDate < currentOnlyDate) {
    // 如果新日期不大于当前日期，则将新日期加一个月
    specificDate.setMonth(specificDate.getMonth() + 1);
  }
  // 比较年月日是否相等
  let isSameDay =
    specificDate.getFullYear() === currentOnlyDate.getFullYear() &&
    specificDate.getMonth() === currentOnlyDate.getMonth() &&
    specificDate.getDay() === currentOnlyDate.getDay();
  let dayDifference = Math.ceil((specificDate - currentOnlyDate) / (1000 * 60 * 60 * 24));

  salary.value = isSameDay?`今天要发工资喽`: `
  距离发工资还有
  <span style="color: red;" >${dayDifference}</span>
  天
  `
}

// 周末
const afterWork = ref()
const getAfterWork = () => {
  // 获取当前时间
  const currentDate = new Date();
  const futureDate = new Date(currentDate);
  futureDate.setDate((currentDate.getDate() + (5 -day.value)))
  futureDate.setHours(Number(infoData.value.closingTime.split(':')[0]))
  futureDate.setMinutes(Number(infoData.value.closingTime.split(':')[1]))
  futureDate.setSeconds(0)
  const timeDifference = futureDate - currentDate
  return timeDifference/1000
}

function getTime() {
  let { dd, hh, mm, ss } = durationFormatter(getWeekend())
  weekend.value = `
  距离下班还有
  <span style="color: red;" >${hh}</span>
  小时
  <span style="color: red;" >${mm}</span>
  分
  <span style="color: red;" >${ss>0?ss: 0}</span>
  秒
  `
  // if(ss){
  //   chrome.runtime.sendMessage({ type: 'COUNT' })
  // }
  let obj = durationFormatter(getAfterWork())
  afterWork.value = `
  距离周末还有
  <span style="color: red;" >${obj.dd}</span>
  天
  <span style="color: red;" >${obj.hh}</span>
  小时
  <span style="color: red;" >${obj.mm}</span>
  分
  <span style="color: red;" >${obj.ss}</span>
  秒
  `
  requestAnimationFrame(getTime);
  // chrome.runtime.sendMessage({ type: 'COUNT', count: count.value })
}
requestAnimationFrame(getTime)

const requestPermission = () => {
  if (!('Notification' in window)) {
    console.log('该浏览器不支持通知');
    return;
  }
  
  Notification.requestPermission().then(permission => {
    if (permission === 'granted') {
      console.log('通知权限已授予');
    }
  });
}

const showNotification = (title, options) => {
  if (Notification.permission === 'granted') {
    new Notification(title, options);
  } else {
    console.log('用户未授予通知权限');
  }
}

const timer = ref()

onMounted(() => {
  requestPermission()
  chrome.storage.sync.get(['setting'], (result) => {
    if(result?.setting){
      formData.value = JSON.parse(result.setting)
      infoData.value = JSON.parse(result.setting)
    }
    getSalary()
  })
  timer.value = setInterval(() => {
    const now = dayjs(new Date()).format('HH:mm:ss')
    if(formData.value.order == now){
      showNotification('该点饭辣！', {
        body: '啥事儿有吃饭重要呐',
        icon: '../../build/img/sss.jpg',
      })
    }
  }, 1000) // 每1秒执行一次
})

onBeforeUnmount(() => {
  clearInterval(timer.value) // 组件卸载时清除定时器
})

const formRef = ref(null)
const submitForm = async ()=>{
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  chrome.storage.sync.set({ setting: JSON.stringify(formData.value) },()=>{
    infoData.value = JSON.parse(JSON.stringify(formData.value))
    getSalary()
    isShow.value = false
  })
}

// watch(count, (newCount) => {
//   chrome.storage.sync.set({ count: newCount })

//   chrome.runtime.sendMessage({ type: 'COUNT', count: count.value })
// })
</script>

<style scoped >
.popup-content {
  width: 400px;
}
.setting{
  display: flex;
  justify-content: flex-end;
}
.tips {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 40px;
  font-size: 20px;
  line-height: 40px;
  border-left: 4px solid #50bfff;
  background-color: #ecf8ff;
  padding: 0 20px;
  color: #4f5b60;
}
.jokeTips {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
  padding-bottom: 6px;
  border-left: 4px solid #50bfff;
  background-color: #ecf8ff;
  padding: 0 20px 6px 20px;
  color: #4f5b60;
}
.timer-box{
  border: 1px solid #c8c5c5;
  border-radius: 5px;
  margin-top: 20px;
}
.timer-item{
  height: 40px;
  line-height: 40px;
  padding: 0 20px;
  border-bottom: 1px solid #c8c5c5;
  font-size: 1.1rem;
}
.timer-item-end{
  border-bottom: none;
}

.card-box{
  margin-top: 10px;
  margin-bottom: 20px;
}
</style>
